﻿<template>
  <a-card :bordered="false">
    <div class="table-operator">
      <a-button type="primary" icon="plus" @click="hanldleAdd()" v-if="hasPerm('agent.Add')">新建</a-button>
      <a-button
        v-if="hasPerm('agent.Delete')"
        type="primary"
        icon="minus"
        @click="handleDelete(selectedRowKeys)"
        :disabled="!hasSelected()"
        :loading="loading"
        >删除</a-button
      >
      <a-button type="primary" icon="redo" @click="getDataList()">刷新</a-button>
    </div>

    <div class="table-page-search-wrapper">
      <a-form layout="inline">
        <a-row :gutter="10">
          <a-col :md="4" :sm="24">
            <a-form-item label="查询类别">
              <a-select allowClear v-model="queryParam.condition">
                <a-select-option key="AgentName">渠道名称</a-select-option>
                <a-select-option key="Phone">电话</a-select-option>
                <a-select-option key="Address">地址</a-select-option>
                <a-select-option key="SettlementAccount">佣金结算账号</a-select-option>
                <a-select-option key="SettlementBank">结算银行</a-select-option>
                <a-select-option key="SuperiorAgentName">上级渠道名称</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="4" :sm="24">
            <a-form-item>
              <a-input v-model="queryParam.keyword" placeholder="关键字" />
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="24">
            <a-button
              type="primary"
              @click="
                () => {
                  this.pagination.current = 1
                  this.getDataList()
                }
              "
              >查询</a-button
            >
            <a-button style="margin-left: 8px" @click="() => (queryParam = {})">重置</a-button>
          </a-col>
        </a-row>
      </a-form>
    </div>

    <a-table
      ref="table"
      :columns="columns"
      :rowKey="(row) => row.Id"
      :dataSource="data"
      :pagination="pagination"
      :loading="loading"
      @change="handleTableChange"
      :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
      :bordered="false"
      size="middle"
    >
      <span slot="action" slot-scope="text, record">
        <template>
          <a @click="handleEdit(record.Id)" v-if="hasPerm('agent.Edit')">编辑</a>
          <a-divider type="vertical" />
          <a-popconfirm
            title="确定删除吗？"
            v-if="hasPerm('agent.Delete')"
            ok-text="确定"
            cancel-text="取消"
            @confirm="handleDelete([record.Id])"
            @cancel="cancel"
          >
            <a href="#">删除</a>
          </a-popconfirm>
          <a-divider type="vertical" />
          <a @click="ConfigService(record)">配置服务商</a>
          <a-divider type="vertical" />
          <a @click="ConfigSign(record)">协议管理</a>
        </template>

        <template slot="CheckStatus" slot-scope="text">
          <span v-if="text == '0'"><a-tag color="blue">待审核</a-tag></span>
          <span v-else><a-tag color="green">审核通过</a-tag></span>
        </template>
      </span>

      <template slot="CheckStatus" slot-scope="text">
        <span v-if="text == '1'"><a-tag color="green">审核通过</a-tag></span>
        <span v-else-if="text == '0'"><a-tag color="blue">待审核</a-tag></span>
        <span v-else><a-tag color="red">审核未通过</a-tag></span>
      </template>
    </a-table>

    <edit-form ref="editForm" :parentObj="this"></edit-form>
    <a-modal title="协议配置" width="70%" :visible="Signvisible" :confirmLoading="loading" @cancel="SignviewCancel">
      <a-collapse accordion>
        <a-collapse-panel key="1" header="渠道信息">
          <a-form-model :model="Signserentity" v-bind="layout">
            <a-form-model-item label="代理商名称" prop="AgentName">
              <a-input v-model="Signserentity.AgentName" autocomplete="off" />
            </a-form-model-item>
            <a-form-model-item label="证件号码" prop="IdNumber">
              <a-input v-model="Signserentity.IdNumber" autocomplete="off" />
            </a-form-model-item>
            <a-form-model-item label="结算银行" prop="SettlementBank">
              <a-input v-model="Signserentity.SettlementBank" autocomplete="off" />
            </a-form-model-item>
            <a-form-model-item label="银行账号" prop="SettlementAccount">
              <a-input v-model="Signserentity.SettlementAccount" autocomplete="off" />
            </a-form-model-item>
            <a-form-model-item label="费率(%)" prop="Rate">
              <a-input v-model="Signserentity.Rate" autocomplete="off" />
            </a-form-model-item>
            <a-form-model-item label="联系人电话" prop="Phone">
              <a-input v-model="Signserentity.Phone" autocomplete="off" />
            </a-form-model-item>
            <a-form-model-item label="联系地址" prop="Address">
              <a-input v-model="Signserentity.Address" autocomplete="off" />
            </a-form-model-item>
            <a-form-model-item label="签约时间" prop="SignDate">
              <a-input v-model="Signserentity.SignDate" autocomplete="off" />
            </a-form-model-item>
          </a-form-model>
        </a-collapse-panel>
        <a-collapse-panel key="2" header="协议信息">
          <a-upload
            list-type="picture"
            :customRequest="selfUpload1"
            :default-file-list="abc"
            :multiple="false"
            :remove="removesignfile"
            :before-upload="beforeUpload"
          >
            <a-button> <a-icon type="upload" /> 选择协议 </a-button>
          </a-upload>
          <div>
            <a-button @click="submitContrat">保存合同</a-button>
          </div>
          <a-table
            ref="table"
            :columns="Signcolumns"
            :rowKey="(row) => row.Id"
            :dataSource="SignData"
            :loading="loading"
            :bordered="false"
            size="middle"
          >
            <span slot="action" slot-scope="text, record">
              <template>
                <a-popconfirm
                  title="确定删除吗？"
                  ok-text="确定"
                  cancel-text="取消"
                  @confirm="SignDelete([record.Id])"
                  @cancel="cancel"
                >
                  <a href="#">删除</a>
                </a-popconfirm>
                <a-divider type="vertical" />
                <a @click="downfile(record)">下载协议</a>
              </template>
            </span>
          </a-table>
        </a-collapse-panel>
      </a-collapse>
      <template slot="footer">
        <a-button @click="SignviewCancel">关闭</a-button>
      </template>
    </a-modal>

    <a-modal title="服务商配置" width="70%" :visible="ConfigSVis" @ok="ConfigServiceSubmit" :confirmLoading="loading" @cancel="ConfigSCancel">
      <a-card title="服务商配置">
        <p>代理商名称：{{ConfigSEntity.AgentName}}</p>
        <div>
          设置签约服务商：
          <a-select show-search option-filter-prop="children" v-model="ConfigSEntity.authorizeSID" style="width:200px" :filter-option="filterOption">
            <a-select-option v-for="(item, index) in ServiceList" :key="index" :value="item.Id">
              {{ item.ServiceName }}
              </a-select-option>
          </a-select>
        </div>
      </a-card>
    </a-modal>
  </a-card>
</template>

<script>
import EditForm from './EditForm'
import OperatorCache from '@/utils/cache/OperatorCache'

const columns = [
  { title: '渠道名称', dataIndex: 'AgentName', width: '15%' },
  // { title: '营业执照号或身份证号码', dataIndex: 'IdNumber', width: '10%' },
  { title: '电话', dataIndex: 'Phone', width: '15%' },
  { title: '地址', dataIndex: 'Address', width: '15%' },


  { title: '所属商务经理名称', dataIndex: 'customerManager', width: '13%' },
  { title: '入驻时间', dataIndex: 'CreateTime', width: '15%' },
  { title: '审核状态', dataIndex: 'CheckStatus', width: '8%', scopedSlots: { customRender: 'CheckStatus' } },

  { title: '操作', dataIndex: 'action',width: '20%', scopedSlots: { customRender: 'action' } },
]
const Signcolumns = [
  { title: '文件名称', dataIndex: 'FileName', width: '30%' },
  { title: '上传时间', dataIndex: 'CreateTime', width: '30%' },
  { title: '操作人', dataIndex: 'CreatorId', width: '30%' },
  { title: '操作', dataIndex: 'action', scopedSlots: { customRender: 'action' } },
]

export default {
  components: {
    EditForm,
  },
  mounted() {
    this.getDataList()
    this.GetService()
  },
  data() {
    return {
      ConfigSEntity:{},
      ConfigSVis:false,
      ServiceList:[],
      SignData: [],
      Signvisible: false,
      abc: [],
      Signserentity: {},
      Signcolumns,
      data: [],
      pagination: {
        current: 1,
        pageSize: 10,
        showTotal: (total, range) => `总数:${total} 当前:${range[0]}-${range[1]}`,
      },
      filters: {},
      sorter: { field: 'Id', order: 'asc' },
      loading: false,
      columns,
      queryParam: {},
      selectedRowKeys: [],
      layout: {
        labelCol: { span: 5 },
        wrapperCol: { span: 18 },
      },
    }
  },
  methods: {
    downfile(row){
      let index = row.ContractdownUrl.lastIndexOf("Upload")
      let spl = row.ContractdownUrl.substr(index)
      console.log(row.ContractdownUrl)
          this.$http.post('/Base_Manage/Upload/downSign',{id:spl},{responseType: 'blob'}).then(res =>{
          const blob = new Blob([res]);
          const fileName = row.FileName;
          const elink = document.createElement('a');// 创建a标签
          elink.download = fileName;// 为a标签添加download属性
          // a.download = fileName; //命名下载名称
          elink.style.display = 'none';
          elink.href = URL.createObjectURL(blob);
          document.body.appendChild(elink);
          elink.click();// 点击下载
          URL.revokeObjectURL(elink.href); // 释放URL 对象
          document.body.removeChild(elink);// 释放标签
      })
    }, 
    removesignfile(){
      this.abc  =[]
    },
    ConfigServiceSubmit(){
      this.$http.post("/Base_leasesystem_agent/leasesystem_agent/SaveData",this.ConfigSEntity).then((res)=>{
        if(res.Success){
          this.$message.success("操作成功")
          this.ConfigSVis = false;
          this.getDataList()
        }else{
          this.$message.error("操作失败")
        }
      })
    },
    ConfigSCancel(){
      this.ConfigSVis = false
    },
    filterOption(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
    },
    GetService(){
      this.$http.post("/Base_Manage/Home/GetService_Select").then((res)=>{
        this.ServiceList = res.Data
      })
    },
    SignDelete(row) {
      this.$http.post("/Base_leasesystem_signfile/leasesystem_signfile/DeleteData",row).then((res)=>{
        if(res.Success){
          this.$message.success("操作成功");
          this.flushSign("Rid",this.Signserentity.FileAttId)
        }else{
          this.$message.error("操作失败")
        }
      })
    },
    flushSign(condition,keyword){
      let temp = {}
      temp.condition = condition
      temp.keyword = keyword
      this.$http.post("/Base_leasesystem_signfile/leasesystem_signfile/GetDataList",{Search: temp}).then((res)=>{
        console.log(res)
        this.SignData = res.Data
      })

    },
    submitContrat() {
      
      if (this.abc.length <= 0) {
        this.$message.error('请先选择需要上传合同')
      } else if(this.abc.length == 1) {
        let temp = {}
        temp.Rid = this.Signserentity.FileAttId
        temp.FileName = this.abc[0].name
        temp.FilePathUrl = this.abc[0].uid
        temp.UpUserName = OperatorCache.info["UserName"]
        temp.UpUserId = OperatorCache.info["Id"]
        temp.ContractdownUrl = this.abc[0].url
        this.$http.post("/Base_leasesystem_signfile/leasesystem_signfile/SaveData",temp).then((res)=>{
          if(res.Success){
            this.$message.success("操作成功")
            this.flushSign("Rid",this.Signserentity.FileAttId)
          }else{
            this.$message.error("操作失败")
          }
        });
        console.log(temp)
      }else{
        this.$message.error('单次上传一个文件，可删除后重新上传')
      }
    },
    beforeUpload(file) {
      let fileType = file.name.split('.')
      const fileDate = fileType.slice(-1)
      if (['xlsx', 'xls', 'doc', 'docx', 'pdf'].indexOf(fileDate[0]) < 0) {
        this.$message.error('仅支持doc,docx,pdf,xls,xlsx 格式')
        return false
      }
    },
    selfUpload1({ action, file, onSuccess, onError, onProgress }) {
      this.loading = true
      const formData = new FormData()
      let that = this
      formData.append('file', file)
      this.$http.post('/Base_Manage/Upload/UploadFileByForm', formData).then((res) => {
        this.abc.push(res)
        console.log(res)
      })
      console.log(file)
    },
    ConfigService(row) {
      this.ConfigSEntity = row
      this.ConfigSVis = true
    },
    ConfigSign(row){
      this.SignData = []
      
      this.abc = []
      this.Signserentity = row
      if(this.Signserentity.FileAttId){
        this.flushSign("Rid",this.Signserentity.FileAttId)
      }
      
      this.Signvisible = true
    },
    handleTableChange(pagination, filters, sorter) {
      this.pagination = { ...pagination }
      this.filters = { ...filters }
      this.sorter = { ...sorter }
      this.getDataList()
    },
    getDataList() {
      this.selectedRowKeys = []

      this.loading = true
      this.$http
        .post('/Base_leasesystem_agent/leasesystem_agent/GetDataList', {
          PageIndex: this.pagination.current,
          PageRows: this.pagination.pageSize,
          SortField: this.sorter.field || 'Id',
          SortType: this.sorter.order,
          Search: this.queryParam,
          ...this.filters,
        })
        .then((resJson) => {
          this.loading = false
          this.data = resJson.Data
          const pagination = { ...this.pagination }
          pagination.total = resJson.Total
          this.pagination = pagination
        })
    },
    onSelectChange(selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys
    },
    hasSelected() {
      return this.selectedRowKeys.length > 0
    },
    hanldleAdd() {
      this.$refs.editForm.openForm()
    },
    handleEdit(id) {
      this.$refs.editForm.openForm(id)
    },
    handleDelete(ids) {
      console.log(ids)
      var thisObj = this

      return new Promise((resolve, reject) => {
        thisObj.$http.post('/Base_leasesystem_agent/leasesystem_agent/DeleteData', ids).then((resJson) => {
          resolve()

          if (resJson.Success) {
            thisObj.$message.success('操作成功!')

            thisObj.getDataList()
          } else {
            thisObj.$message.error(resJson.Msg)
          }
        })
      })
    },
    cancel(e) {
      this.$message.error('已取消删除')
    },
    SignviewCancel() {
      this.Signvisible = false
    },
  },
}
</script>

<style>
.ant-table-thead > tr > th
{
  font-weight: 600;
  color: #333333;
}
</style>